#include <iostream>
#include <unistd.h>
#include <thread>
#include <vector>
#include <mutex>
#include "mtx.hpp"
#define NUM 3 // 线程数量
using namespace std;

int val = 10;
thread_local int t_val = 0;
mutex mut;

void fun(string name)
{
    while (1)
    {
        {
            //mtx m;
            mut.lock();
            if (val > 0)
            {
                usleep(10000);
                t_val++;
                val--;
                cout << name << " get one" << " total: " << t_val << " val: " << val << endl;
                mut.unlock();
            }
            else
            {
                mut.unlock();
                break;
            }
        }
        usleep(2);
    }
}

int main()
{
    thread trd[NUM];
    // 创建多个线程
    for (int i = 0; i < NUM; i++)
    {
        string name = "thread" + to_string(i + 1);
        trd[i] = thread(fun, name);
    }
    // 等待线程
    for (int i = 0; i < NUM; i++)
    {
        trd[i].join();
    }
    return 0;
}